Dictionaries

Creating a Dict


In [1]:
dct = dict()
print(type(dct), dct)


<class 'dict'> {}

In [2]:
dct = {}
print(type(dct), dct)


<class 'dict'> {}

In [3]:
dct = {'a': 1}
print(type(dct), dct)


<class 'dict'> {'a': 1}

Adding some items


In [4]:
dct['b'] = 2
dct


Out[4]:
{'a': 1, 'b': 2}

In [5]:
dct['a'] = 3
dct


Out[5]:
{'a': 3, 'b': 2}

In [6]:
dct['b']


Out[6]:
2

In [7]:
#dct['c']

#---------------------------------------------------------------------------
#KeyError                                  Traceback (most recent call last)
#<ipython-input-12-3e4d85f12902> in <module>()
#----> 1 dct['c']
#
#KeyError: 'c'

In [8]:
len(dct)


Out[8]:
2

In [9]:
print('a' in dct)
print('c' in dct)


True
False

In [10]:
values = dct.values()
print(values)


dict_values([3, 2])

In [11]:
def histogram(s: str) -> dict:
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

In [12]:
hist = histogram("This is a test and a Hello World".lower())
print(hist)


{'t': 3, 'h': 2, 'i': 2, 's': 3, ' ': 7, 'a': 3, 'e': 2, 'n': 1, 'd': 2, 'l': 3, 'o': 2, 'w': 1, 'r': 1}

In [13]:
def histogram(s: str) -> dict:
    d = dict()
    for c in s:
        d[c] = d.get(c, 0) + 1
        
    return d

In [14]:
hist = histogram("This is a test and a Hello World".lower())
print(hist)


{'t': 3, 'h': 2, 'i': 2, 's': 3, ' ': 7, 'a': 3, 'e': 2, 'n': 1, 'd': 2, 'l': 3, 'o': 2, 'w': 1, 'r': 1}

In [15]:
def print_histogram(dct: dict) -> None:
    for key, value in dct.items():
        print(key, value)

In [16]:
print_histogram(hist)


t 3
h 2
i 2
s 3
  7
a 3
e 2
n 1
d 2
l 3
o 2
w 1
r 1

In [17]:
def print_histogram(dct: dict) -> None:
    for key in sorted(dct):
        print(key, dct[key])

In [18]:
print_histogram(hist)


  7
a 3
d 2
e 2
h 2
i 2
l 3
n 1
o 2
r 1
s 3
t 3
w 1

In [19]:
def print_histogram(dct: dict) -> None:
    for key, value in sorted(dct.items()):
        print(key, value)

In [20]:
print_histogram(hist)


  7
a 3
d 2
e 2
h 2
i 2
l 3
n 1
o 2
r 1
s 3
t 3
w 1

In [21]:
def reverse_lookup(dct: dict, value: int) -> str:
    for key in dct:
        if dct[key] == value:
            return key
    else:
        raise LookupError('value does not appear in the dictionary')

In [22]:
print(reverse_lookup(histogram('parrot'), 2))


r

In [23]:
#print(reverse_lookup(histogram('parrot'), 3))

#---------------------------------------------------------------------------
#LookupError                               Traceback (most recent call last)
#<ipython-input-45-0d81dc02c5ce> in <module>()
#----> 1 print(reverse_lookup(histogram('parrot'), 3))
#
#<ipython-input-43-dcc62d669299> in reverse_lookup(dct, value)
#      4             return key
#      5     else:
#----> 6         raise LookupError('value does not appear in the dictionary')
#
#LookupError: value does not appear in the dictionary

In [24]:
known = {0:0, 1:1}

def fibonacci(n: int) -> int:
    if n in known:
        return known[n]
    res = fibonacci(n-1) + fibonacci(n-2)
    known[n] = res
    return res

In [25]:
for i in range(10):
    print("fib({}): {}".format(i, fibonacci(i)))
    print(known)


fib(0): 0
{0: 0, 1: 1}
fib(1): 1
{0: 0, 1: 1}
fib(2): 1
{0: 0, 1: 1, 2: 1}
fib(3): 2
{0: 0, 1: 1, 2: 1, 3: 2}
fib(4): 3
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
fib(5): 5
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5}
fib(6): 8
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8}
fib(7): 13
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13}
fib(8): 21
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21}
fib(9): 34
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34}